package net.sxnic.normal.util;

import java.io.File;
import java.util.List;

import net.sxnic.ugr.permission.Permission;
import net.sxnic.ugr.permission.PermissionManager;
import net.sxnic.ugr.resource.Resource;
import net.sxnic.ugr.resource.ResourceManager;
import net.sxnic.ugr.role.Role;
import net.sxnic.ugr.role.RoleManager;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PermissionUtils {
	
	private static Logger logger = LoggerFactory.getLogger(PermissionUtils.class);

	public static void readPermissionFromFile(File file,
			PermissionManager perManager, ResourceManager resManager,
			RoleManager roleManager) throws Exception {

		if (file == null) {
			return;
		}

		List<String> list = FileUtils.readLines(file,"UTF-8");

		String[] r_s = null;
		Permission p = null;
		Resource res = null;
		Role role = null;
		for (String line : list) {
			if (StringUtils.isBlank(line) || line.startsWith("#")) {
				continue;
			}

			r_s = StringUtils.split(line.trim(), ",");

			p = perManager.findByUnique("code", r_s[1]);

			if (p == null) {
				p = new Permission();
			}

			p.setUrl(r_s[0]);
			p.setCode(r_s[1]);
			p.setBeizhu(r_s[2]);
			// p.setr(r_s[3]);

			if (StringUtils.isNotBlank(r_s[3]) && "#".equals(r_s[3])) {

			} else {
				res = resManager.findByUnique("code", r_s[3]);
				if (res == null) {
					 throw new Exception("无法查找到权限"+r_s[3]+"相对应的资源");
				}
				
				p.setRes(res);

				if (StringUtils.isBlank(r_s[4]) || "#".equals(r_s[4])) {
					p.setOpt(Permission.ANY);
				} else {									
					p.setOpt(r_s[4]);									
					p.treatUrl();
				}
			}
			
			perManager.save(p);
			logger.debug("====权限信息更新成功===="+p.getUrl());
			
			if(StringUtils.isNotBlank(r_s[5]) && !"#".equals(r_s[5])){
				String[] roles = StringUtils.split(r_s[5],"/");
				for(String roleCode:roles){
					role = roleManager.findByUnique("role", roleCode);
					if(role ==null){
						throw new Exception("无法查找到权限"+p.getCode()+"相对应的角色"+r_s[5]);
					}else{
						if(!role.getPermissions().contains(p)){
							role.getPermissions().add(p);
							roleManager.update(role);
							logger.debug("====权限加入角色成功===role="+role.getRole());
						}
					}
				}
			}
		}
	}
}
